package com.xuecheng.web.interceptors;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

@Slf4j
public class AuthInfoInterceptor implements HandlerInterceptor {
    /**
     * 前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器，解析token");
        //获取请求头：payload
        String json = request.getHeader("payload");
        if (StringUtils.isEmpty(json)) {
            return true;
        }
        //转化编码
        String decode = URLDecoder.decode(json, "UTF-8");
        log.info("ddd="+decode);
        //将json转换为java对象
        AuthInfo info = JSON.parseObject(decode, AuthInfo.class);
        //存入ThradLocal中
        AuthInfoHolder.setAuthInfo(info);
        return true;
    }

    //在响应结束之前
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
